<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI聊天助手</title>
    <style>
        body {
            font-family: 'Arial', sans-serif;
            margin: 0;
            padding: 0;
            background-color: #f5f5f5;
            display: flex;
        }
        .sidebar {
            width: 250px;
            background-color: white;
            height: 100vh;
            box-shadow: 2px 0 5px rgba(0, 0, 0, 0.1);
            transition: transform 0.3s ease;
            overflow-y: auto;
            z-index: 10;
        }
        .sidebar-header {
            padding: 15px;
            border-bottom: 1px solid #eee;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .sidebar-title {
            font-weight: bold;
            color: #4a6fa5;
        }
        .toggle-sidebar {
            background: none;
            border: none;
            font-size: 20px;
            cursor: pointer;
            color: #4a6fa5;
        }
        .history-list {
            list-style: none;
            padding: 0;
            margin: 0;
        }
        .history-item {
            padding: 12px 15px;
            border-bottom: 1px solid #eee;
            cursor: pointer;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        .history-item:hover {
            background-color: #f0f0f0;
        }
        .history-item.active {
            background-color: #e6f0ff;
            color: #4a6fa5;
        }
        .main-content {
            flex-grow: 1;
            display: flex;
            justify-content: center;
            padding: 20px;
        }
        .chat-container {
            background-color: white;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            overflow: hidden;
            width: 100%;
            max-width: 800px;
        }
        .chat-header {
            background-color: #4a6fa5;
            color: white;
            padding: 15px;
            text-align: center;
            font-size: 18px;
            font-weight: bold;
        }
        .chat-messages {
            height: 400px;
            overflow-y: auto;
            padding: 15px;
        }
        .message {
            margin-bottom: 15px;
            display: flex;
        }
        .user-message {
            justify-content: flex-end;
        }
        .bot-message {
            justify-content: flex-start;
        }
        .message-content {
            max-width: 70%;
            padding: 10px 15px;
            border-radius: 18px;
            word-wrap: break-word;
        }
        .user-message .message-content {
            background-color: #4a6fa5;
            color: white;
        }
        .bot-message .message-content {
            background-color: #e5e5ea;
            color: black;
        }
        .chat-input {
            display: flex;
            padding: 15px;
            border-top: 1px solid #eee;
        }
        #user-input {
            flex-grow: 1;
            padding: 10px 15px;
            border: 1px solid #ddd;
            border-radius: 20px;
            outline: none;
        }
        #send-button {
            margin-left: 10px;
            padding: 10px 20px;
            background-color: #4a6fa5;
            color: white;
            border: none;
            border-radius: 20px;
            cursor: pointer;
        }
        #send-button:hover {
            background-color: #3a5a80;
        }
        .typing-indicator {
            display: none;
            padding: 10px 15px;
            background-color: #e5e5ea;
            border-radius: 18px;
            margin-bottom: 15px;
            width: fit-content;
        }
        .typing-dot {
            display: inline-block;
            width: 8px;
            height: 8px;
            border-radius: 50%;
            background-color: #888;
            margin: 0 2px;
            animation: typingAnimation 1.4s infinite ease-in-out;
        }
        .typing-dot:nth-child(1) {
            animation-delay: 0s;
        }
        .typing-dot:nth-child(2) {
            animation-delay: 0.2s;
        }
        .typing-dot:nth-child(3) {
            animation-delay: 0.4s;
        }
        @keyframes typingAnimation {
            0%, 60%, 100% { transform: translateY(0); }
            30% { transform: translateY(-5px); }
        }
        .sidebar-toggle {
            position: fixed;
            left: 10px;
            top: 10px;
            background-color: #4a6fa5;
            color: white;
            border: none;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            font-size: 20px;
            cursor: pointer;
            z-index: 100;
            display: none;
        }
        @media (max-width: 768px) {
            .sidebar {
                position: fixed;
                transform: translateX(-100%);
            }
            .sidebar.visible {
                transform: translateX(0);
            }
            .sidebar-toggle {
                display: block;
            }
        }
    </style>
</head>
<body>
<button class="sidebar-toggle" id="sidebar-toggle">≡</button>
<div class="sidebar" id="sidebar">
    <div class="sidebar-header">
        <div class="sidebar-title">历史会话</div>
        <button class="toggle-sidebar" id="toggle-sidebar">×</button>
    </div>
    <ul class="history-list" id="history-list">
        <!-- 历史会话将通过JavaScript动态加载 -->
    </ul>
</div>

<div class="main-content">
    <div class="chat-container">
        <div class="chat-header">
            AI聊天助手
        </div>
        <div class="chat-messages" id="chat-messages">
            <div class="typing-indicator" id="typing-indicator">
                <span class="typing-dot"></span>
                <span class="typing-dot"></span>
                <span class="typing-dot"></span>
            </div>
        </div>
        <div class="chat-input">
            <input type="text" id="user-input" placeholder="输入您的问题..." autocomplete="off">
            <button id="send-button">发送</button>
        </div>
    </div>
</div>

<script>
    cid = crypto.randomUUID();
    document.addEventListener('DOMContentLoaded', function() {
        const chatMessages = document.getElementById('chat-messages');
        const userInput = document.getElementById('user-input');
        const sendButton = document.getElementById('send-button');
        const typingIndicator = document.getElementById('typing-indicator');
        const sidebar = document.getElementById('sidebar');
        const toggleSidebar = document.getElementById('toggle-sidebar');
        const sidebarToggle = document.getElementById('sidebar-toggle');
        const historyList = document.getElementById('history-list');

        // 加载历史会话
        function loadChatHistory() {
            fetch('/chat/history')
                .then(response => {
                    if (!response.ok) {
                        throw new Error('获取历史会话失败');
                    }
                    return response.json();
                })
                .then(data => {
                    historyList.innerHTML = '';
                    if (data && data.length > 0) {
                        data.forEach(chat => {
                            const li = document.createElement('li');
                            li.className = 'history-item';
                            li.textContent = chat.title || `会话 ${new Date(chat.timestamp).toLocaleString()}`;
                            li.dataset.id = chat.id;
                            li.addEventListener('click', () => loadChat(chat.id));
                            historyList.appendChild(li);
                        });
                    } else {
                        const emptyMsg = document.createElement('li');
                        emptyMsg.textContent = '暂无历史会话';
                        emptyMsg.style.padding = '15px';
                        emptyMsg.style.color = '#999';
                        historyList.appendChild(emptyMsg);
                    }
                })
                .catch(error => {
                    console.error('获取历史会话出错:', error);
                });
        }

        // 加载特定聊天记录
        function loadChat(chatId) {
            fetch(`/chat/history/${chatId}`)
                .then(response => {
                    if (!response.ok) {
                        throw new Error('获取聊天记录失败');
                    }
                    return response.json();
                })
                .then(data => {
                    chatMessages.innerHTML = '';
                    if (data && data.messages) {
                        data.messages.forEach(msg => {
                            if (msg.role === 'user') {
                                addUserMessage(msg.content);
                            } else {
                                addBotMessage(msg.content);
                            }
                        });
                    }
                    // 更新当前活跃的历史项
                    document.querySelectorAll('.history-item').forEach(item => {
                        item.classList.remove('active');
                        if (item.dataset.id === chatId) {
                            item.classList.add('active');
                        }
                    });
                })
                .catch(error => {
                    console.error('加载聊天记录出错:', error);
                    addBotMessage("加载历史会话时出错。");
                });
        }

        // 添加用户消息到聊天界面
        function addUserMessage(message) {
            const messageDiv = document.createElement('div');
            messageDiv.className = 'message user-message';

            const contentDiv = document.createElement('div');
            contentDiv.className = 'message-content';
            contentDiv.textContent = message;

            messageDiv.appendChild(contentDiv);
            chatMessages.appendChild(messageDiv);
            chatMessages.scrollTop = chatMessages.scrollHeight;
        }

        // 添加AI消息到聊天界面
        function addBotMessage(message) {
            const messageDiv = document.createElement('div');
            messageDiv.className = 'message bot-message';

            const contentDiv = document.createElement('div');
            contentDiv.className = 'message-content';
            contentDiv.textContent = message;

            messageDiv.appendChild(contentDiv);
            chatMessages.appendChild(messageDiv);
            chatMessages.scrollTop = chatMessages.scrollHeight;
        }

        // 发送消息到后端API
        function sendMessage() {
            const message = userInput.value.trim();
            if (message === '') return;

            addUserMessage(message);
            userInput.value = '';

            // 显示"正在输入"指示器
            typingIndicator.style.display = 'block';
            chatMessages.scrollTop = chatMessages.scrollHeight;

            // 编码用户输入
            const encodedMessage = encodeURIComponent(message);
            const apiUrl = `http://localhost:8080/chat/ask?q=${encodedMessage}&&cid=` + cid;

            // 调用API
            fetch(apiUrl)
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应不正常');
                    }
                    return response.json();
                })
                .then(data => {
                    // 隐藏"正在输入"指示器
                    typingIndicator.style.display = 'none';

                    // 假设API返回的数据结构中有answer字段
                    const answer = data.answer || data.response || "抱歉，我无法理解这个问题。";
                    addBotMessage(answer);

                    // 发送消息后刷新历史会话列表
                    loadChatHistory();
                })
                .catch(error => {
                    // 隐藏"正在输入"指示器
                    typingIndicator.style.display = 'none';

                    console.error('获取数据时出错:', error);
                    addBotMessage("抱歉，发生错误，无法获取回答。");
                });
        }

        // 点击发送按钮发送消息
        sendButton.addEventListener('click', sendMessage);

        // 按Enter键发送消息
        userInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                sendMessage();
            }
        });

        // 切换侧边栏显示/隐藏
        toggleSidebar.addEventListener('click', () => {
            sidebar.classList.toggle('visible');
        });

        // 移动端切换侧边栏按钮
        sidebarToggle.addEventListener('click', () => {
            sidebar.classList.toggle('visible');
        });

        // 初始欢迎消息
        setTimeout(() => {
            addBotMessage("您好！我是AI助手，请问有什么可以帮您的吗？");
            // 加载历史会话
            loadChatHistory();
        }, 500);
    });
</script>
</body>
</html>